package org.jash.mdm.model

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.jash.common.mvi.BaseState
import org.jash.common.mvi.BaseViewModel
import org.jash.common.net.retrofit
import org.jash.mdm.entity.LockEntity
import org.jash.mdm.net.LockService

class LockViewModel:BaseViewModel<LockIntent, LockState>() {
    val service: LockService by lazy { retrofit.create(LockService::class.java) }
    fun checkLocked(check: LockIntent.CheckLocked) {
        viewModelScope.launch {
            try {
                val locked = service.checkLocked()
                if (locked.statusCode != 200) {
                    val white = service.getWhite()
                    if (white.statusCode == 200) {
                        state.value = LockState.Response(LockEntity(false, white.data))
                    } else {
                        state.value = BaseState.Error(white.msg)
                    }
                } else {
                    state.value = LockState.Response(LockEntity(true, null))
                }
            } catch (e:Exception) {
                state.value = BaseState.Error(e.message ?: "")
            }

        }
    }
    fun start(start:LockIntent.Start) {
        viewModelScope.launch {
            for (i in start.count downTo 0) {
                state.value = LockState.Progress(i)
                delay(1000)
            }
            state.value = LockState.Finish("结束")
        }
    }
}